/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.se2.meteocal.control;

import it.polimi.se2.meteocal.entity.Event;
import it.polimi.se2.meteocal.entity.Participation;
import it.polimi.se2.meteocal.entity.Users;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Ugo
 */
@Stateless
public class ParticipationManager {
    @PersistenceContext
    public EntityManager emp;
     
    public void create(Participation entity) {
        emp.persist(entity);
    }
      
    public void edit(Participation entity) {
        emp.merge(entity);
    }

    public void remove(Participation entity) {
        emp.remove(emp.merge(entity));
    }
    
    public List<Participation> findParticipationByUser(Users user) {
        return emp.createNamedQuery(Participation.findByUser, Participation.class)
                .setParameter("user", user)
                .setParameter("state", Participation.State.PENDING)
                .getResultList();          
    }
     
    public List<Participation> findParticipationByEvent(Event event) {
        return emp.createNamedQuery(Participation.findByEvent, Participation.class)
                .setParameter("event", event)
                .getResultList(); 
    }
     
    public Participation findParticipationByEventUser(Event event, Users user) {
          try{
          return emp.createNamedQuery(Participation.findByEventUser, Participation.class)
                .setParameter("event", event)
                .setParameter("user", user)
                .getSingleResult(); 

          }
           catch(NoResultException e){
            return null;
        }
     }
    
    public List<Participation> findParticipationByEventNotRemoved(Event event) {
          try{
        return emp.createNamedQuery(Participation.findByEventNotRemoved, Participation.class)
                .setParameter("event", event)
                .getResultList(); 
        }
           catch(NoResultException e){
            return null;
        }
    }

    
}